<template>
  <div class="budget-data-container">
    <!-- 按课题显示预算数据 -->
    <el-card
      v-for="topicData in groupedBudgetData"
      :key="topicData.topicId"
      class="topic-budget-card"
    >
      <div slot="header" class="clearfix">
        <span>课题: {{ topicData.topicName }}</span>
      </div>

      <!-- 树形表格显示预算数据 -->
      <el-table
        :data="topicData.treeData"
        row-key="subjectId"
        :indent="30"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        border
        default-expand-all
        size="small"
      >
        <el-table-column prop="subjectName" label="预算科目" min-width="200">
          <template #default="{ row }">
            <span :style="{
              marginLeft: `${(row.subjectLevel - 1) * 20}px`,
              fontWeight: row.subjectLevel === 1 ? 'bold' : 'normal'
            }">
              {{ row.subjectName }}
              <el-tag v-if="row.isSummary" size="mini" type="info" style="margin-left: 8px">汇总项</el-tag>
            </span>
          </template>
        </el-table-column>

        <el-table-column label="财政经费(万元)" width="150" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.fiscalFunds) }}
          </template>
        </el-table-column>

        <el-table-column label="自筹经费(万元)" width="150" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.selfFunds) }}
          </template>
        </el-table-column>

        <el-table-column label="合计(万元)" width="120" align="right">
          <template #default="{ row }">
            {{ formatNumber((row.fiscalFunds || 0) + (row.selfFunds || 0)) }}
          </template>
        </el-table-column>


      </el-table>
    </el-card>
  </div>
</template>

<script>
import { budgetDetailList } from "@/api/sci/budget";

export default {
  name: "BudgetData",
  props: {
    projectId: {
      type: [String, Number], // 根据实际类型选择
      default: null
    },
  },
  data() {
    return {
      rawBudgetData: [], // 原始扁平数据
      groupedBudgetData: [] // 按课题分组的数据
    };
  },
  created() {
    this.loadBudgetData();
  },
  watch: {
    projectId: {
      handler(newVal, oldVal) {
        // 只有当projectId有效且发生变化时才重新加载数据
        if (newVal && newVal !== oldVal) {
          this.loadBudgetData();
        }
      },
      immediate: true // 立即触发一次
    }
  },
  methods: {
    // 加载预算数据
    async loadBudgetData() {
      // 处理空值情况
      if (!this.projectId) {
        this.rawBudgetData = [];
        this.groupedBudgetData = [];
        return;
      }

      try {
        const response = await budgetDetailList(this.projectId);
        this.rawBudgetData = response.data || [];
        this.processBudgetData();
      } catch (error) {
        console.error("加载预算数据失败:", error);
        this.$message.error("加载预算数据失败");
        // 出错时清空数据
        this.rawBudgetData = [];
        this.groupedBudgetData = [];
      }
    },

    // 处理预算数据：分组并构建树形结构
    processBudgetData() {
      // 1. 按topicId分组
      const topicGroupMap = new Map();

      this.rawBudgetData.forEach(item => {
        if (!topicGroupMap.has(item.topicId)) {
          topicGroupMap.set(item.topicId, {
            topicId: item.topicId,
            topicName: item.topicName,
            items: []
          });
        }
        topicGroupMap.get(item.topicId).items.push(item);
      });

      // 2. 为每组数据构建树形结构
      this.groupedBudgetData = Array.from(topicGroupMap.values()).map(topicGroup => {
        return {
          topicId: topicGroup.topicId,
          topicName: topicGroup.topicName,
          treeData: this.buildTree(topicGroup.items),
          items: topicGroup.items
        };
      });
    },

    // 构建树形结构
    buildTree(flatData) {
      // 创建映射以便快速查找节点
      const nodeMap = new Map();
      const roots = [];

      // 初始化所有节点
      flatData.forEach(item => {
        nodeMap.set(item.subjectId, {
          subjectId: item.subjectId,
          parentId: item.parentId,
          sortOrder: item.sortOrder,
          editable: item.editable === 1,
          isSummary: item.isSummary === 1,
          fiscalFunds: item.fiscalFunds || 0,
          selfFunds: item.selfFunds || 0,
          subjectName: item.subjectName,
          subjectLevel: item.subjectLevel,
          children: []
        });
      });

      // 构建父子关系
      flatData.forEach(item => {
        const node = nodeMap.get(item.subjectId);
        const parentId = item.parentId;

        if (parentId === "0" || parentId === 0 || !nodeMap.has(parentId)) {
          // 根节点
          roots.push(node);
        } else {
          // 子节点
          const parent = nodeMap.get(parentId);
          if (parent) {
            parent.children.push(node);
          }
        }
      });

      // 对每个层级进行排序
      const sortNodes = (nodes) => {
        nodes.sort((a, b) => a.sortOrder - b.sortOrder);
        nodes.forEach(node => {
          if (node.children && node.children.length) {
            sortNodes(node.children);
          }
        });
      };

      sortNodes(roots);
      return roots;
    },

    // 格式化数字显示
    formatNumber(value) {
      if (value === null || value === undefined) return "0.00";
      return parseFloat(value).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
  }
};
</script>

<style scoped>
.budget-data-container {
  padding: 20px;
}

.topic-budget-card {
  margin-bottom: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>
